/**
 * PHOSIDE: PHosphorylation Site IDentification Engine.
 * Copyright 2009 Digital Biology Lab, University of Missouri.
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version. <p/> This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more
 * details.
 */

package phoside.io.fasta.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;

/**
 *
 * @author gjj
 */
public class FastaReaderTraveler implements FastaTraveler {
    final Reader fastaReader;
    final FastaVisitor visitor;

    public FastaReaderTraveler(final Reader fastaReader,
            final FastaVisitor visitor) {
        if (fastaReader==null || visitor==null) {
            throw new NullPointerException();
        }

        this.fastaReader = fastaReader;
        this.visitor = visitor;
    }

    public void travel() throws IOException {
        if (visitor==null) {
            throw new NullPointerException("Must specify a visitor.");
        }
        
        BufferedReader in = new BufferedReader(fastaReader);

        String header = new String();
        StringBuilder sequence = new StringBuilder();

        int count = 0;

        String line = in.readLine();
        while (true) {
            while (line!=null && line.trim().length()==0) {
                line = in.readLine();
            }

            if (line==null) {
                if (header.length()>0 && sequence.length()>0) {
                    visitor.visit(header, sequence.toString());
                }

                break;
            }

            line = line.trim();

            if (line.startsWith(">")) { //header
                if (count++%1000==0) {
                    System.out.println(String.format("%10d", count));
                }

                if (header.length()>0 && sequence.length()>0) {
                    visitor.visit(header, sequence.toString());
                }

                header = line.substring(1);
                sequence = new StringBuilder();
            } else {
                sequence.append(line);
            }

            line = in.readLine();
        }
    }
}
